<template>
    <div class="goods-add-form">
        <div class="section">
            <h2 class="section-title">基础信息</h2>
            <el-form ref="ruleFormRef" style="max-width: 1200px;margin: 20px;" :model="data" status-icon
                :rules="rules" label-width="auto" class="demo-ruleForm">
                <el-form-item label="采购退货单号" prop="purret_code">
                    <el-input v-model="data.purret_code" placeholder="采购退货单号" disabled />
                </el-form-item>
                <div style="display: flex; justify-content: space-between;">
                    <div style="width: 48%;">
                        <el-form-item label="关联采购单号" style="margin-bottom: 30px;">
                            <el-input v-model="data.po_code" placeholder="关联采购单号" disabled />
                        </el-form-item>
                        <el-form-item label="供应商名称" style="margin-bottom: 30px;">
                            <el-input v-model="data.vendor_name" placeholder="供应商名称" disabled />
                        </el-form-item>
                        <el-form-item label="退货日期" prop="purret_returntime" style="margin-bottom: 30px;">
                            <el-date-picker v-model="data.purret_returntime" type="date" width="460"
                                placeholder="请选择退货日期" :size="size" style="width: 460px;" :editable="false"/>
                        </el-form-item>
                    </div>

                    <div style="width: 48%;">
                        <el-form-item label="联系人" style="margin-bottom: 30px;">
                            <el-input v-model="data.contacts_name" placeholder="联系人" disabled />
                        </el-form-item>
                        <el-form-item label="联系方式" style="margin-bottom: 30px;">
                            <el-input v-model="data.contacts_phone" placeholder="联系方式" disabled />
                        </el-form-item>
                        <el-form-item prop="warehouse_code" label="退货仓库" style="margin-bottom: 30px;">
                            <el-select v-model="data.warehouse_code" placeholder="请选择退货仓库">
                                <el-option v-for="item in CKOptions" :key="item.warehouse_code"
                                    :label="item.warehouse_name" :value="item.warehouse_code" />
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
                <el-form-item label="退货原因" prop="purret_returncause">
                    <el-input v-model="data.purret_returncause" placeholder="请输入退货原因" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="data.remark" placeholder="请输入备注" />
                </el-form-item>
            </el-form>
        </div>

        <div class="section">
            <h2 class="section-title">退货产品明细</h2>
            <el-table :data="selectedData" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{
                    textAlign: 'center',
                    background: '#f5f7fa',
                    fontWeight: 'bold',
                    position: 'sticky',
                    top: 0
                }" ref="selectedTable">
                <el-table-column prop="pro_name" label="货品名称" />
                <el-table-column prop="pro_code" label="货品编号" width="160" />
                <el-table-column prop="pro_brand" label="品牌" width="100" />
                <el-table-column prop="pro_model" label="规格型号" />
                <el-table-column prop="unitmeas_id" label="单位" width="70">
                    <template #default="scope">
                        <span>{{ measureValue(scope.row.unitmeas_id) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="po_number" label="采购数量" />
                <el-table-column prop="podet_inbound_quantity" label="已入库数量"/>
                <el-table-column prop="podet_notstocked" label="未入库数量">
                    <template #default="scope">
                        <span>{{ scope.row.po_number - scope.row.podet_inbound_quantity }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="podet_retqty" label="本次退货数量">
                    <template #default="scope">
                        <el-input v-model="scope.row.podet_retqty" style="width: 75px" :precision="2" :min="0" 
                            :max="scope.row.podet_inbound_quantity" @change="validateReturnQty(scope.row)" />
                    </template>
                </el-table-column>
            </el-table>
            <div style="height: 40px; line-height: 40px;">
                <div style="display: inline-block; float: left;">合计</div>
                <div style="display: inline-block; float:right">退货总数量：{{ return_total_qty }}
                </div>
            </div>
        </div>

        <div class="button-group" style="position: absolute; bottom: 10px; right: 64px; display: flex; gap: 10px;">
            <el-button @click="handleAdd">保存</el-button>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>
</template>

<script>
import { ref, reactive, onMounted, inject, watch } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useStore } from 'vuex';

export default {
    setup() {
        const store = useStore()
        const rowData = store.state.PO_UpdeteArray

        const data = reactive({
            purret_id: "",
            purret_code: "",
            po_id: "",
            po_code: "",
            vendor_name: "",
            vendor_code: "",
            contacts_name: "",
            contacts_phone: "",
            purret_returntime: "",
            warehouse_code: "",
            purret_returncause: "",
            pu_state: "1",
            remark: "",
            del_flag: "0",
            update_by: localStorage.getItem('userLName'),
            update_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ')
        });

        const ruleFormRef = ref(null);
        const rules = reactive({
            purret_code: [
                { required: true, message: "退货单号不能为空", trigger: "blur" },
            ],
            purret_returntime: [
                { required: true, message: "退货日期不能为空", trigger: "blur" },
            ],
            purret_returncause: [
                { required: true, message: "退货原因不能为空", trigger: "blur" },
            ]
        });

        const Router = useRouter();
        const route = useRoute();
        // let rowData = {};
        
        // // 解码URI组件
        // const decodedData = decodeURIComponent(route.query.rowData);
                
        // // 解析JSON
        // rowData = JSON.parse(decodedData);

        const CKOptions = ref([]);
        const selectedData = ref([]);
        const return_total_qty = ref(0);


        // 获取计量单位选项
        const measureOptios = ref([]);
        
        // 初始化数据
        function initData() {
            // 填充基础信息
            Object.keys(rowData).forEach(key => {
                if (key in data) {
                    // 特殊处理日期字段
                    if (key === 'purret_returntime' && rowData[key]) {
                        data[key] = convertToLocalDateTime(rowData[key]);
                    } else {
                        data[key] = rowData[key];
                    }
                }
            });
            
            // 填充明细数据
            if (rowData.details && Array.isArray(rowData.details)) {
                selectedData.value = rowData.details.map(item => {
                    return {
                        ...item,
                        podet_retqty: item.podet_retqty || 0
                    };
                });
            } else {
                console.warn("没有找到明细数据或明细数据格式不正确");
                selectedData.value = [];
            }
        }
        
        // 获取仓库选项
        function getCK() {
            axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBySelect", {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                CKOptions.value = result.data;
            }).catch((err) => {
                console.error('获取仓库列表失败:', err);
                ElMessage.error('获取仓库列表失败');
            });
        }
        
        

        
        // 获取计量单位
        function getMeasure() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "db_measure"
                }, 
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                measureOptios.value = result.data;
            }).catch((err) => {
                console.error('获取计量单位失败:', err);
            });
        }
        
        // 根据计量单位ID获取名称
        function measureValue(row) {
            if (!row) return "无";
            const measure = measureOptios.value.find(item => item.dict_value == row);
            return measure ? measure.dict_label : "无";
        }
        
        // 验证退货数量
        function validateReturnQty(row) {
            if(row.podet_retqty>row.po_number-row.number_returns){
                    ElMessage.warning('退货数量不能大于未入库数量');
                    row.podet_retqty = row.po_number-row.number_returns;
                }
        }
        
        // 保存数据
        function handleAdd() {
            ruleFormRef.value.validate(async (valid) => {
                if (valid) {
                    if (selectedData.value.length === 0) {
                        ElMessage.warning('请填写退货产品明细');
                        return;
                    }
                    
                    // 检查是否有退货数量为0的项
                    const hasZeroReturn = selectedData.value.some(item => item.podet_retqty <= 0);
                    if (hasZeroReturn) {
                        ElMessage.warning('退货数量必须大于0');
                        return;
                    }
                    
                    updateReturn();
                }
            });
        }

        // 计算退货总数
        watch(selectedData, (newVal) => {
            return_total_qty.value = 0;
            newVal.forEach(row => {
                return_total_qty.value += Number(row.podet_retqty) || 0;
            });
        }, {deep: true,
            immediate: true
        })
        function convertToLocalDateTime(dateStr) {
            // 处理可能的空格分隔符
            const normalizedStr = dateStr.replace(' ', 'T') + 'Z';
            const dateObj = new Date(normalizedStr);
            
            // 增加8小时转为GMT+8
            dateObj.setUTCHours(dateObj.getUTCHours() + 8);
            
            // 返回特定格式的字符串
            return dateObj;
        }
        
        // 更新退货单
        function updateReturn() {
            const Pu_details_Update_Dto = selectedData.value.map(item => ({
                podet_id: item.podet_id,
                podet_retqty: item.podet_retqty,
            }));

            const Pinv_Pu_Order_Dto = {
                return_Order_Dto: {
                    purret_id: data.purret_id,
                    po_code: data.po_code,
                    purret_returntime: data.purret_returntime,
                    warehouse_code: data.warehouse_code,
                    purret_returncause: data.purret_returncause,
                    remark: data.remark,
                    update_by: localStorage.getItem('userLName'),
                    update_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
                },
                return_detailsDto: Pu_details_Update_Dto
            };
            console.log(Pinv_Pu_Order_Dto)
            const Updatedata={
                Pinv_Pu_Order_Dto:Pinv_Pu_Order_Dto.return_Order_Dto,
                Pu_details_Update_Dto:Pinv_Pu_Order_Dto.return_detailsDto
            }
            // console.log(Updatedata)
            axios.put("http://localhost:5181/api/Pu/PutPuUpdate", Updatedata, {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                if (result.data > 0) {
                    ElMessage({
                        type: 'success',
                        message: '采购退货单修改成功！'
                    });
                    handleClose();
                } else {
                    ElMessage.warning('未更新任何数据');
                }
            }).catch((err) => {
                console.error('更新退货单失败:', err);
                ElMessage.error('更新退货单失败: ' + (err.response?.data?.message || err.message));
            });
        }
        
        // 关闭页面
        const closeTab = inject('closeTab');
        function handleClose() {
            const targetPath = "/main/Pinv/Pu";

            if (closeTab) {
                closeTab();
            }

            const tabs = inject('editableTabs');
            if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
                tabs.value.push({
                    title: "采购退货",
                    name: targetPath,
                    path: targetPath
                });
            }

            const activeTab = inject('editableTabsValue');
            if (activeTab) {
                activeTab.value = targetPath;
            }

            Router.push(targetPath);
        }

        onMounted(() => {
            getCK();
            getMeasure();
            initData();
        });

        return {
            data,
            CKOptions,
            selectedData,
            return_total_qty,
            ruleFormRef,
            rules,
            measureValue,
            handleAdd,
            handleClose,
            validateReturnQty
        }
    }
}
</script>

<style scoped>
.goods-add-form {
    padding: 20px;
    background-color: #fff;
    margin-top: -40px;
}

.section {
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    margin-top: -20px;
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.1%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px;
}
</style>